from sqlalchemy.ext.asyncio import AsyncSession as Session
from sqlmodel import select, func
from app.models.waveup.swap_stat import SwapStat
from app.schemas.waveup.swap_stat import SwapStatCreate, SwapStatUpdate
from fastapi.exceptions import HTTPException
from app.core.utils import cents_to_yuan_str

async def create_swap_stat(session: Session, swap_stat_in: SwapStatCreate) -> SwapStat:
    """创建Waveup交易对兑换统计"""
    db_swap_stat = SwapStat.model_validate(swap_stat_in)
    session.add(db_swap_stat)
    await session.commit()
    await session.refresh(db_swap_stat)
    return db_swap_stat

async def get_swap_stat(session: Session, uid: int, product_pair_id: str = "") -> SwapStat:
    """获取Waveup交易对兑换统计"""
    statement = select(SwapStat).where(SwapStat.uid == uid, SwapStat.productPairId == product_pair_id)
    result = await session.execute(statement)
    return result.scalar_one_or_none()

async def get_swap_stat_by_id(session: Session, swap_stat_id: int) -> SwapStat:
    """根据ID获取Waveup交易对兑换统计"""
    return await session.get(SwapStat, swap_stat_id)

# 更新waveup交易对兑换统计（兑换次数及累计收益）
async def update_swap_stat(
    session: Session,
    swap_stat_in: SwapStatUpdate,
) -> SwapStat:
    """更新Waveup交易对兑换统计"""
    # 1. 从数据库查询交易对兑换统计
    db_swap_stat = await get_swap_stat_by_id(session=session, swap_stat_id=swap_stat_in.id)
    if not db_swap_stat:
        raise HTTPException(status_code=404, detail="WaveUp交易对兑换统计不存在")
    db_swap_stat.swapCount += swap_stat_in.swapCount
    db_swap_stat.swapAmount += swap_stat_in.swapAmount
    session.add(db_swap_stat)
    await session.commit()
    await session.refresh(db_swap_stat)
    return db_swap_stat

# 查询用户所有交易对兑换统计
async def get_all_swap_stat(session: Session, uid: int):
    """获取用户所有Waveup交易对兑换统计"""
    statement = select(
        func.sum(SwapStat.swapCount).label("swapCount"), 
        func.sum(SwapStat.swapAmount).label("swapAmount")
    ).where(SwapStat.uid == uid)
    # 2. 执行查询
    result = await session.execute(statement)
    row = result.one_or_none()
    # 3. 处理查询结果
    swapCount, swapAmount = row if row else (0, 0)
    return {
        "swapCount": swapCount or 0,
        "swapAmount": cents_to_yuan_str(swapAmount) or "0.00",
    }
